function retry(promiseFunction, times) {
    return new Promise((resolve, reject) => {
        const attempt = (attemptNumber) => {
            promiseFunction()
                .then(resolve)
                .catch((error) => {
                    if (attemptNumber < times) {
                        console.log(`Attempt ${attemptNumber + 1} failed. Retrying...`);
                        attempt(attemptNumber + 1);
                    } else {
                        reject(`All ${times} attempts failed.`);
                    }
                });
        };

        attempt(0);
    });
}

// 示例用法
const simulateFailingRequest = () => {
    const random = Math.random();
    if (random > 0.5) {
        return Promise.resolve('Request succeeded');
    } else {
        return Promise.reject('Request failed');
    }
};

retry(simulateFailingRequest, 3)
    .then((result) => {
        console.log(result); // 在最多3次尝试后成功的情况下，打印出 'Request succeeded'
    })
    .catch((error) => {
        console.error(error); // 如果所有尝试都失败，打印出 'All 3 attempts failed.'
    });
